package 异常处理;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Demo2 {


    public static void a() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个整数:");
        int num1, index, num2, result;
        try {
            num1 = scanner.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("输入不合法!");
            num1 = 10;
        }
        index = (int) (Math.random() * 12);
        int[] arr = {3, 0, 4, 0, 0, 0, 0, 0, 0};
        try {
            num2 = arr[index];
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("数组下标越界啦!");
            num2 = 2;
        }
        try {
            result = num1 / num2;
        } catch (ArithmeticException e) {
            System.out.println("除数不能为0");
            result = -1;
        }
        System.out.println("除法结果为" + result);
    }


    private static void b() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个整数:");
        int num1, num2, result = 0;
        try {
            System.out.print("请输入一个数：");
            num1 = scanner.nextInt(); // 有可能出现异常 输入异常
            int[] array = {6, 9, 8, 0, 0, 0, 6, 0, 5, 0};
            int index = (int) (Math.random() * 12);
            System.out.println("随机生成的索引号是：" + index);
            num2 = array[index]; // 有可能出现数组越界了
            System.out.println("另一个数是：" + num2);
            result = num1 / num2; // 有可能出现数学异常
        } catch (ArithmeticException e) {
            System.out.println("除数不能为0");
            result = 1;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("数组下标越界了");
            num2 = 2;
        } catch (InputMismatchException e) {
            System.out.println("输入的不合法");
            num1 = 10;
        }
        System.out.println("结果是" + result);
    }

    public static void main(String[] args) {
//        a();
        b();
    }
}
